from fastapi import APIRouter, Depends, HTTPException, Request, status, Query, Body
from sqlalchemy.orm import Session
from typing import List

from app.database.database import get_db
from app.database.repository.user_repository import UserRepository
from app.exception.code_exception import CodeException
from app.schemas.account import AccountDTO
from app.schemas.user import UserCreate, UserUpdate, UserDTO
from app.core.pagination import Pageable, Page
from app.schemas.rr import RR, SuccessView
from app.services.account_service import AccountService
from app.services.user_service import UserService
from app.models.models import User
import logging

from app.utils.request_utils import RequestUtils
logger = logging.getLogger(__name__)

router = APIRouter(prefix="/user", tags=["user"])

@router.post("/create", response_model=RR[UserDTO], status_code=status.HTTP_201_CREATED)
async def create(user: UserCreate, db: Session = Depends(get_db)):
    user_service = UserService(db)
    created_user = user_service.create_user(user)
    return RR.success(created_user)

@router.get("/list", response_model=RR[Page[UserDTO]])
async def list(
    pageable: Pageable = Depends(),
    db: Session = Depends(get_db)
):
    page = UserRepository(db).find_page(pageable=pageable)
    
    # 记录日志
    for user in page.items:
        logger.info(f"User ID: {user.id}, Name: {user.name}, Account: {user.account}")
    
    return RR.success(page)

@router.get("/{user_id}", response_model=RR[UserDTO])
async def get_user(user_id: int, db: Session = Depends(get_db)):
    user = UserRepository(db).find_by_id(user_id)
    if not user:
        raise CodeException.resource_not_found("User")
    return RR.success(user)

@router.put("/{user_id}", response_model=RR[UserDTO])
async def update_user(user_id: int, user_update: UserUpdate, db: Session = Depends(get_db)):
    user_service = UserService(db)
    updated_user = user_service.update_user(user_id, user_update)
    return RR.success(updated_user)

@router.put("/{user_id}/reset-password", response_model=SuccessView)
async def reset_password(user_id: int, newPwd: str = Body(..., min_length=6, description="新密码"), db: Session = Depends(get_db)):
    user_service = UserService(db)
    user_service.reset_password(user_id, newPwd)
    return SuccessView.create()

@router.get("/profile", response_model=RR[dict])
async def profile(request: Request, db: Session = Depends(get_db)):
    """
    获取当前用户的个人信息
    
    Args:
        current_user: 当前登录用户
        
    Returns:
        RR[UserResponse]: 当前用户信息
    """
    user = RequestUtils.login_user_and_check(request, db)
    account = AccountService(db).get_account_by_user_id(user.id)
    return RR.success({
        "user": UserDTO.model_validate(user),
        "account": AccountDTO.model_validate(account)
    })
